package com.yangxd.system.service.auth;

import com.yangxd.system.entity.TbRole;
import com.yangxd.system.entity.TbUser;
import com.yangxd.system.entity.UserRole;
import com.yangxd.system.service.TbRoleService;
import com.yangxd.system.service.TbUserService;
import com.yangxd.system.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: yangxudong
 * @Date: 2021/4/20 18:17
 * @Version 1.0
 */
/*
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private TbRoleService tbRoleService;

    */
/**
     * 通过用户名称查询用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     *//*

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(username == null || "".equals(username) ) {
            throw new RuntimeException("用户名称不能为空");
        }
        //如果不为空，通过用户名查询用户
        TbUser tbUser = tbUserService.selectByName(username);
        if(tbUser == null) {
            throw new UsernameNotFoundException(String.format("%s这个人不存在",username));
        }
        //如果存在则查询该用户具有的角色
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //
        List<UserRole> userRoleList = userRoleService.listByUserId(tbUser.getId());
        userRoleList.forEach(userRole -> {
                    TbRole roleTable = tbRoleService.selectById(userRole.getRoleId());
                    authorities.add(new SimpleGrantedAuthority(roleTable.getRoleName()));
                }
        );
        return new User(tbUser.getUsername(),new BCryptPasswordEncoder().encode(tbUser.getPassword()),authorities);
    }
}
*/
